import React from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { CircularProgress, Box } from '@mui/material';

const ProtectedRoute = ({ children }) => {
    const { isAuthenticated, loading } = useAuth();
    const location = useLocation();

    // 正在加载认证状态
    if (loading) {
        return (
            <Box
                display="flex"
                justifyContent="center"
                alignItems="center"
                minHeight="100vh"
            >
                <CircularProgress />
            </Box>
        );
    }

    // 未认证，重定向到登录页面
    if (!isAuthenticated()) {
        // 传递当前位置，以便登录后返回
        return <Navigate to="/login" state={{ from: location }} replace />;
    }

    // 已认证，渲染子组件
    return children;
};

export default ProtectedRoute; 